package com.gxa.uhome.controller;

import com.gxa.uhome.mapper.SlipMapper;
import com.gxa.uhome.pojo.*;
import com.gxa.uhome.util.JsonResult;
import com.gxa.uhome.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Laiguowei
 * @date: 14:09 2021/6/10
 **/

@RestController
@CrossOrigin
@RequestMapping("/slip")
@Api(tags = "购物凭条模块")
public class SlipController {

    @Resource
    SlipMapper slipMapper = null;

    @PostMapping("/upload")
    @ApiOperation("获得用户订单的详情")
    @ApiImplicitParam(name = "id", value = "用户订单id", dataType = "int")
    public JsonResult getDetail(@Autowired HttpServletRequest request ,@RequestParam String imgIndex, @RequestParam("file") MultipartFile file) {

        JsonResult jsonResult = new JsonResult();
        String fileName = UploadUtil.getFileName(file);

//        System.out.println("当前名字"+fileName);
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                String path = this.getClass().getClassLoader().getResource("").getPath();
//                System.out.println(path);
                String rootPath = System.getProperty("rootPath");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                // 写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
                file.transferTo(serverFile);

                //将当前的用户的img地址存到session
                request.getSession().setAttribute(imgIndex,fileName);
                jsonResult.setMsg("You successfully uploaded file=" + fileName);
                jsonResult.setCode("1");
            } catch (Exception e) {
                jsonResult.setMsg("You failed to upload " + fileName + " => " + e.getMessage());
            }
        } else {
            jsonResult.setMsg("You failed to upload " + fileName + " because the file was empty.");
        }
        return jsonResult;
    }






}


